import {httpGetResponse, httpSuccessPost} from '@/utils/ajax'
import {alert, confirm, dotData} from '@/utils'
import store from '@/store'

// type: 1,商家对师傅，2客服对商家和师傅，3,师傅对商家
export function getImUserExt(orderNo, orderId, type = 1) {
  let p1 = httpGetResponse('/ms-fahuobao-order/im/query-create-group-order', {orderNo, type}).then(response => {
    if (response.success) {
      const data = response.data || {}
      if (data !== false) {
        return data
      }
    }
    return Promise.reject(new Error('创建聊天组失败'))
  }).catch(_ => {
    return Promise.reject(new Error('创建聊天组失败'))
  })
  let p2 = httpGetResponse('/ms-fahuobao-order/FhbOrder/findFhbOrderParticulars', {orderId}).then(response => {
    if (response.success) {
      const data = response.data || {}
      if (data !== false) {
        return data
      }
    }
    return Promise.reject(new Error('订单信息获取失败'))
  }).catch(_ => {
    return Promise.reject(new Error('订单信息获取失败'))
  })

  return Promise.all([p1, p2]).then(arr => {
    let groupId = arr[0]['groupId']
    if (arr[0] && arr[1]) {
      let consigneeAddress = `${dotData(arr[1], 'fhbOrderConsigneeInfo.consigneProvince', '')} ${dotData(arr[1], 'fhbOrderConsigneeInfo.consigneCity', '')} ${dotData(arr[1], 'fhbOrderConsigneeInfo.consigneDistrict', '')} ${dotData(arr[1], 'fhbOrderConsigneeInfo.consigneAddress', '')}`
      let ext = {
        userId: dotData(arr[1], 'fhbOrderBiddingLog.peopleUserId'), // 师傅id
        userName: dotData(arr[1], 'fhbOrderBiddingLog.name'), // 师傅名称
        userPhoto: dotData(arr[1], 'fhbOrderBiddingLog.peoplePicture'), // 师傅头像
        userPhone: dotData(arr[1], 'fhbOrderBiddingLog.peopleUserPhone'), // 师傅电话
        businessId: dotData(arr[1], 'fhbOrder.founder'), // 商家id
        businessName: dotData(arr[1], 'fhbOrder.founderName'), // 商家名称
        businessPhoto: '', // 商家头像
        goodsPicture: dotData(arr[1], 'fhbOrderGoods[0].picture'),
        business: dotData(arr[1], 'fhbOrder.business'),
        service: dotData(arr[1], 'fhbOrder.service'),
        serviceMoney: String(dotData(arr[1], 'fhbOrderBidding.price')),
        consigneeName: dotData(arr[1], 'fhbOrderConsigneeInfo.consigneName'),
        consigneePhone: dotData(arr[1], 'fhbOrderConsigneeInfo.consignePhone'),
        consigneeAddress: consigneeAddress,
        orderNo: orderNo,
        totalBalse: String(dotData(arr[1], 'fhbOrder.totalPackage')),
        groupId: arr[0]['groupId']
      }
      return {ext, groupId}
    }
  }).then(({ext, groupId}) => {
    // 根据 groupid 获取群成员
    return httpGetResponse('/ms-message-im/easemobUser/findEasemobGroupListByGroup', {groupId}).then(response => {
      if (response.success) {
        const data = response.data || {}
        if (data !== false) {
          let members = handUser(data.easemobGroupUserList, data.name)
          // 当前的groupId 对应的信息
          store.dispatch('SET_IM_CHART_DIALOG_GROUP_ID_INFO', {
            groupId: groupId,
            info: {
              members, // 用户信息
              orderNo: data.businessId, // 订单信息
              inArbitration: type === 2 ? 1 : 0 // 是否处于仲裁
            }
          })
          // 设置当前groupId
          return {groupId, ext}
        }
      }
      return Promise.reject(new Error('群组成员获取失败'))
    }).then(({groupId, ext}) => {
      // 创建成功
      if (groupId) {
        store.dispatch('SET_IM_CHART_DIALOG_GROUP_ID', groupId)
      }
      store.dispatch('SET_IM_CHART_DIALOG_VISIBLE', {visible: true})
      return {groupId, ext}
    }).catch(_ => {
      return Promise.reject(new Error('群组成员获取失败'))
    })
  })
}

// 根据订单号获取订单信息
export function getImUserExtByOrderNo(orderNo) {
  return httpGetResponse('/ms-fahuobao-order/FhbOrder/findFhbOrderParticularsIm', {businessId: orderNo}).then(response => {
    if (response.success) {
      const data = response.data || {}
      let consigneeAddress = `${dotData(data, 'fhbOrderConsigneeInfo.consigneProvince', '')} ${dotData(data, 'fhbOrderConsigneeInfo.consigneCity', '')} ${dotData(data, 'fhbOrderConsigneeInfo.consigneDistrict', '')} ${dotData(data, 'fhbOrderConsigneeInfo.consigneAddress', '')}`
      if (data !== false) {
        return {
          userId: dotData(data, 'fhbOrderBiddingLog.peopleUserId'), // 师傅id
          userName: dotData(data, 'fhbOrderBiddingLog.name'), // 师傅名称
          userPhoto: dotData(data, 'fhbOrderBiddingLog.peoplePicture'), // 师傅头像
          userPhone: dotData(data, 'fhbOrderBiddingLog.peopleUserPhone'), // 师傅电话
          businessId: dotData(data, 'fhbOrder.founder'), // 商家id
          businessName: dotData(data, 'fhbOrder.founderName'), // 商家名称
          businessPhoto: '', // 商家头像
          goodsPicture: dotData(data, 'fhbOrderGoods[0].picture'),
          business: dotData(data, 'fhbOrder.business'),
          service: dotData(data, 'fhbOrder.service'),
          serviceMoney: String(dotData(data, 'fhbOrderBidding.price')),
          consigneeName: dotData(data, 'fhbOrderConsigneeInfo.consigneName'),
          consigneePhone: dotData(data, 'fhbOrderConsigneeInfo.consignePhone'),
          consigneeAddress: consigneeAddress,
          orderNo: orderNo,
          totalBalse: String(dotData(data, 'fhbOrder.totalPackage'))
        }
      }
    }
    return false
  })
}

// 处理环信的用户信息
export function handUser(arr, name) { // 获取用户的基本信息
  let temp = []
  if (Array.isArray(arr)) {
    arr.forEach(v => {
      temp.push({
        userName: v.userName,
        userPhoto: v.userPhoto,
        userType: v.userType,
        userEasemobName: v.userEasemobName,
        userId: v.userId
      })
    })
  }
  return temp
}

// 初始聊天组
export function getInitMembers() {
  httpGetResponse('/ms-message-im/easemobUser/findEasemobGroupList').then(response => {
    if (response.success) {
      const data = response.data
      if (data !== false) {
        if (Array.isArray(data)) {
          store.dispatch('CLEAR_IM_CHART_DIALOG_GROUP_ID_INFO')
          data.forEach((v, k) => {
            // 处理用户
            let members = handUser(v.easemobGroupUserList, v.name)
            // 当前的groupId 对应的信息
            store.dispatch('SET_IM_CHART_DIALOG_GROUP_ID_INFO', {
              groupId: v.groupId,
              info: {
                members, // 用户信息
                orderNo: v.businessId, // 订单信息
                inArbitration: parseInt(v.inArbitration) || 0, // 是否处于仲裁
                name: v.name
              }
            })
          })
        }
      }
    }
  })
}

// 检查用户是否加入了群聊
export function checkUserGroup(orderNo) {
  return httpGetResponse('/ms-message-im/easemobUser/checkUserGroup', {businessId: orderNo}).then(response => {
    if (response.success) {
      return !!response.data
    }
    return false
  })
}

// 加入或退出群聊
export function joinOrOutIm(showImDialog, type, orderNo, orderId) {
  if (showImDialog) {
    // 退出群聊
    store.dispatch('REMOVE_IM_CHART_DIALOG_GROUP_MEMBERS_BY_ORDER_NO', orderNo)
    return httpSuccessPost('/ms-message-im/easemobUser/delUserToGroup', {businessId: orderNo}).then(response => {
      const success = dotData(response, 'success')
      if (success) {
        confirm('退出成功', undefined, {type: 'success'})
        return true
      }
      return false
    })
  } else {
    return joinIm(orderNo, orderId, type)
  }
}

// 加入群聊
export function joinIm(orderNo, orderId, type) {
  return getImUserExt(orderNo, orderId, type).then(() => {
    return true
  }).catch(err => {
    alert(err.message)
  })
}

// 跳转历史
export function showHistoryList(orderNo) {
  return httpGetResponse('/ms-message-im/easemobUser/findEasemobLogByBusiness', {businessId: orderNo}).then(response => {
    const success = response.success
    if (success) {
      const groupId = response.data
      if (groupId) {
        // 设置当前的group
        store.dispatch('SET_IM_CHART_DIALOG_GROUP_ID', groupId)
        store.dispatch('SET_NOTICE_TYPE', '4')
        // 设置订单的信息
        store.dispatch('SET_IM_CHART_DIALOG_GROUP_ID_INFO', {groupId, info: {orderNo}})
        // 设置为只读消息
        store.dispatch('SET_IM_READ_ONLY_GROUP_ID', {groupId})
        return groupId
      } else { // 暂时历史
        alert('此订单没有聊天记录')
        return Promise.reject(new Error('此订单没有聊天记录'))
      }
    }
    return Promise.reject(new Error('获取历史消息组失败'))
  })
}
